import {Button, Form, Input, Space, Table, Tag, Typography} from 'antd';
import React, {useEffect, useState} from 'react';
import '../index.css'
import message from "antd/es/message";
import {AllSubjects} from "@/services/DashApi";
import SchoolLogo from "../../../../../config/logos/SchoolLogo";
import {history} from 'umi'
import {ReadOutlined, SearchOutlined, TableOutlined, UnorderedListOutlined} from "@ant-design/icons";

const SearchModule = (props) => {

  const {onFilterName} = props

  return (
    <Form
      name="basic"
      layout="inline"
      labelCol={{span: 8}}
      wrapperCol={{span: 16}}
      initialValues={{remember: true}}
      onFinish={(values) => {
        onFilterName(values.keyword)
      }}
      autoComplete="off"
    >
      <Space>
        <Form.Item
          name="keyword"
        >
          <Input style={{width: 163}} name="searchValue" placeholder="请输入关键字"/>
        </Form.Item>
        <Button
          htmlType="submit"
        >
          <SearchOutlined /> 搜索
        </Button>
        <Button
          type="default"
          onClick={() => {
            onFilterName("")
          }}
        >
          <UnorderedListOutlined /> 全部
        </Button>
      </Space>
    </Form>
  )
}


function getSchoolName(name) {
  return name.split('-')[0]
}

const App = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [reload, setReload] = useState(false)
  const [data, setData] = useState([])

  useEffect(() => {
    setLoading(true)
    AllSubjects().then(response => {
      console.log("@AllSubjects", response)
      if (response.status === 0) {
        let data = []
        for (let i = 0; i < response.data.length; i++) {
          data.push({
            name: response.data[i].univ_name + "-" + response.data[i].discipline_name,
            key: i,
            tag: response.data[i].tag.split('、')
          })
        }
        setData(data)
      }
      setLoading(false)
    }, () => {
      setLoading(false)
    })
  }, [reload])

  const [originDataSource, setOriginDataSource] = useState([])

  const clear = () => {
    setSelectedRowKeys([])
  }

  // 搜索逻辑
  const handleFilter = (keyword) => {
    if (!keyword) keyword = ""
    console.log(data)
    let od = originDataSource
    if (originDataSource.length === 0) {
      setOriginDataSource(data)
      od = data
    }
    const originDataSourceF = od
    const dataF = originDataSourceF.filter((current) => {
      return current.name.indexOf(keyword) !== -1 || current.tag.includes(keyword)
    })
    setData(dataF)
    clear()
  }


  // 开始对比
  const start = () => {
    // setLoading(true); // ajax request after empty completing
    //
    // setTimeout(() => {
    //   setSelectedRowKeys([]);
    //   setLoading(false);
    // }, 1000);
    let subjects = []
    for (let i = 0; i < selectedRowKeys.length; i++) {
      for (let j = 0; j < data.length; j++) {
        if (data[j].key === selectedRowKeys[i]) {
          subjects.push(data[j])
        }
      }
      // subjects.push(data[selectedRowKeys[i]])
    }
    console.log(subjects)
    let url = '/province/subject_compare/detail/'
    for (let i = 0; i < subjects.length; i++) {
      url += subjects[i].name
      if (i < subjects.length - 1) {
        url += '_'
      }
    }
    history.push(url)
  };

  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    if (newSelectedRowKeys.length <= 3) {
      setSelectedRowKeys(newSelectedRowKeys);
    } else {
      message.warn("最多选择3项")
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  const columns = [
    {
      title: <span>请选择学科或学科群<Typography.Text strong>（点击<Tag style={{marginLeft: 8}} color="blue">蓝色</Tag>标签可快速分类、全部按钮可显示所有学科）</Typography.Text></span>,
      dataIndex: 'name',
      render: (text, key, idx) => {
        return <div id={text}><img src={SchoolLogo[getSchoolName(text)]}
                         style={{width: 25, height: 25, marginBottom: 3, marginRight: 5}}/>
          <span className="good-content-size">{text}</span>
          {data[idx].tag.map((item, idx) => {
            return <Tag style={{
              marginLeft: 5,
              marginBottom: 5,
              cursor: "pointer"
            }} color="blue"
            onClick={() => {
              handleFilter(item)
            }} key={item}
            >{item}</Tag>
          })}
        </div>
      },
    },
  ];

  return (
    <div>
      <Space
        style={{
          marginBottom: 16,
        }}
      >
        <div style={{marginRight: 20}}>
          <Button type="primary" onClick={start} disabled={!hasSelected}>
            <ReadOutlined /> 学科对比
          </Button>
          &nbsp;
          {/*<Button type="default" onClick={clear}>*/}
          {/*  清空*/}
          {/*</Button>*/}
          <span
            style={{
              marginLeft: 8,
            }}
          >
          {hasSelected ? `您已选中 ${selectedRowKeys.length} 项` : ''}
        </span>
        </div>

        <SearchModule onFilterName={handleFilter}/>
      </Space>
      <Table loading={loading} pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data}/>
    </div>
  );
};

export default App;
